import base64
import pickle

from django.shortcuts import render
from django.views import View
import json
from django import http
from apps.goods.models import SKU
from django_redis import get_redis_connection


# Create your views here.
class CartsView(View):
    """购物车管理"""

    def post(self, request):
        """添加购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        # 没有传，就给他默认值
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '商品不存在'})
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.JsonResponse({'code': 400, 'errmsg': '参数count有误'})
        # 判断selected是否为bool值
        if selected:
            # isinstance 检验参数类型是否正确
            if not isinstance(selected, bool):
                return http.JsonResponse({'code': 400, 'errmsg': '参数selected有误'})

        # 判断用户是否登录
        if request.user.is_authenticated:
            # 用户已登录，操作 redis 购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 新增购物车数据
            # hincrby 这个命令是为哈希表中的key 中的域field 的值增量 count  count可以为负数，就是减
            pl.hincrby('carts_%s' % request.user.id, sku_id, count)
            # 新增选中的状态
            if selected:
                pl.sadd('selected_%s' % request.user.id, sku_id)
            # 执行管道
            pl.execute()

            # 响应结果
            return http.JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})

        else:
            # 用户未登录，操作 cookie 购物车
            # 获取的是字符串类型
            cookie_cart = request.COOKIES.get('carts')
            # 如果用户操作过 cookie 购物车
            if cookie_cart:
                # 将 cookie_cart 转成 base64 的 bytes,最后将 bytes 转字典
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                # 用户从没有操作过 cookie 购物车
                cart_dict = {}

            # 判断要加入购物车的商品是否已经在购物车中
            # 如有相同商品，累加求和，反之，直接赋值
            # 我们判断用户之前是否将该商品加入过购物车, 如果加入过
            # 则只需要让数量增加即可.
            # 如果没有存在过, 则需要创建, 然后增加:
            # 形式如下所示:
            # {
            #     '<sku_id>': {
            #         'count': '<count>',
            #         'selected': '<selected>',
            #     },
            #     ...
            # }
            if sku_id in cart_dict:
                # 累加求和
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将字典转成 bytes,再将 bytes 转成 base64 的 bytes
            # 最后将bytes转字符串
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            response = http.JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})
            # 响应结果并将购物车数据写入到 cookie
            response.set_cookie('carts', cart_data)

            return response

    def get(self, request):
        """展示购物车页面"""
        if request.user.is_authenticated:
            # 登录用户
            redis_conn = get_redis_connection('carts')
            # 获取 redis 中的购物车数据，hash存的
            cart_item_dict = redis_conn.hgetall('carts_%s' % request.user.id)
            # 获取 redis 中的选中状态，set存的
            cart_selected = redis_conn.smembers('selected_%s' % request.user.id)

            # 把redis数据库里的数据转成字典形式好返回
            cart_dict = {}
            for sku_id, count in cart_item_dict.items():  # 遍历字典的key 和value
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected  # sku_id in cart_selected 在就返回true 不在返回false
                }

        else:
            # 未登录用户
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()  # 从字典里获取所以的keys
        skus = SKU.objects.filter(id__in=sku_ids)  # 利用这写 id 查找所有对应的商品sku
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count'),
            })

        # 渲染购物车页面
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})

    def put(self, request):
        """修改购物车页面数据"""
        # 逻辑与新增购物车数据95%相同
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        # 没有传，就给他默认值
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '商品不存在'})
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.JsonResponse({'code': 400, 'errmsg': '参数count有误'})
        # 判断selected是否为bool值
        if selected:
            # isinstance 检验参数类型是否正确
            if not isinstance(selected, bool):
                return http.JsonResponse({'code': 400, 'errmsg': '参数selected有误'})

        # 判断用户是否登录
        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # hset 覆盖写入
            pl.hset('carts_%s' % request.user.id, sku_id, count)
            # 勾选添加，没勾选就删除这个  不是逻辑问题 不存在的删除不会报错
            if selected:
                pl.sadd('selected_%s' % request.user.id, sku_id)
            else:
                pl.srem('selected_%s' % request.user.id, sku_id)
            pl.execute()

            # 返回数据给前端 更新页面
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 把要修改的数据直接覆盖旧的数据
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 返回数据给前端页面
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': cart_sku})
            response.set_cookie('carts', cookie_cart_str)
            return response

    def delete(self,request):
        """购物车数据删除"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code':400,'errmsg':'参数sku_id不存在'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 删除哈希的 set中的sku_id
            pl.hdel('carts_%s' % request.user.id,sku_id)
            pl.srem('selected_%s' % request.user.id, sku_id)
            pl.execute()

            return http.JsonResponse({'code':0,'errmsg':'ok'})

        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 解密
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 传过来的商品是否在字典里
            if sku_id in cart_dict:
                # 删除数据，字典数据
                del cart_dict[sku_id]

            # 加密 存cookie
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response = http.JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('carts',cart_str)
            return response


class CartSelectAllView(View):
    """全选购物车"""
    def put(self,request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.JsonResponse({'code':400,'errmsg':'参数selected有误'})

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % request.user.id)
            # 获取所有的商品id
            sku_ids = item_dict.keys()

            if selected:
                # 全选 *sku_ids 拆包 官网上就是这样写的sadd(key,*value)
                redis_conn.sadd('selected_%s' % request.user.id, *sku_ids)
            else:
                redis_conn.srem('selected_%s' % request.user.id, *sku_ids)

            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            cart_str = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            # 有cookie就加密解密，没有就直接返回
            if cart_str:
                # 解密
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

                for sku_id in cart_dict.keys():
                    cart_dict[sku_id]['selected'] = selected

                # 加密 存cookie
                cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cart_str)

            return response